package com.lsk.api;

import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.util.*;
import org.eclipse.jetty.util.UrlEncoded;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class Mifeng {

    public static String userCode = "13189770088";
    public static String password = "hzijy2020";
    public static String cardSubmitUrl = "http://www.mf178.cn/api/open";
    public static String appkey = "86299700";
    public static String appSecret = "bca71e680bfa52b8e3ebb4151ecc14cb";

    static Cache cache = Redis.use();

    /**
     * 卡id
     *
     * @param record
     */
    public static void cardSubmit(Record record) {

        String cacheCardId = record.getStr("id");

        String id = record.getStr("commodityId");

        //查出来对应的 commodity 信息
        String commoditySql="SELECT *from commodity where id='"+id+"'";

        Record commodityRecord=Db.findFirst(commoditySql);

        String name=commodityRecord.getStr("name");

        try {

            String card_type="0";

            String confiSql = "SELECT `value` from sys_config where element='domain'";

            String domain = Db.queryStr(confiSql);

            Map<String, Object> parameters = new LinkedHashMap<>();




            if (name.contains("移动")){

                card_type="1";

            }else if (name.contains("联通")){

                card_type="2";

            }else if (name.contains("电信")){

                card_type="3";

            }else if (name.contains("中石化")){

                card_type="4";

            }else if (name.contains("中石油")){

                parameters.put("recovery_type","2");//卡密回收类型，只有卡密是为2， 包含卡密和卡号是为8

                card_type="18";

            }else {

                Syslog.info("未匹配到对应信息");

            }

            parameters.put("action","card_upload");

            parameters.put("app_key",appkey);


            parameters.put("attach", record.getStr("id"));



            parameters.put("callback_url", UrlEncoded.encodeString( "http://"+domain.replace("http://",""))+"/mobile/mifengCallback");

            parameters.put("card_type",card_type);


            String cardNumber=record.getStr("cardNumber");

            String cardPassword=record.getStr("cardPassword");


            if ("18".equals(card_type)){
                // 只有卡密
                parameters.put("data",cardNumber);

            }else {

                parameters.put("data",UrlEncoded.encodeString( cardNumber+" "+cardPassword));
            }


            parameters.put("face_type",record.getStr("feedbackValue"));



            String time=System.currentTimeMillis()+"";

            time=time.substring(0,10);

            int intTime=Integer.parseInt(time);


            parameters.put("recovery_type","8");//卡密回收类型，只有卡密是为2， 包含卡密和卡号是为8

            parameters.put("time",intTime);

            parameters.put("token",getToken());

            String sign=sign(parameters);

            parameters.put("sign",sign);


            String cardNo = record.getStr("cardNumber");

            if ("".equals(cardNo) || cardNo==null){
                Syslog.info("无卡号卡种");
            }else {
                //parameters.put("cardNo", cardNo);
            }

            //String cardPwd = record.getStr("cardPassword");


            //String dateTime = DateUtil.getSdfTimes();


            String userOrderNo = "MF" + DateUtil.getSdfTimes() + Tools.getRandomNum();


            String result = HttpKit.post(cardSubmitUrl,JsonUtil.getJsonStr(parameters));

            Syslog.info("蜜蜂收卡传递参数" + JsonUtil.getJsonStr(parameters));    //打印收卡网参数
            System.out.println(result);
            Syslog.info("蜜蜂收卡返回结果" + result);

            Map<String, Object> resultMap = new HashMap<>();

            resultMap = JsonUtil.getMapFromJsonObjStr(result);
            /**
             * 状态码
             */
            String code = resultMap.get("ret").toString();

            String SkreturnMsg=resultMap.get("msg").toString();
            /**如果返回消息,则使用返回消息*/

            String afterSubmitCardState ="";
            if(code.equals("0")){
                afterSubmitCardState="2";// 推送成功
            }else{
                afterSubmitCardState="3";//推送失败,将不再回调

            }

            String cardId = record.getStr("id");
            Db.update("update card set state=?,msg=? where id =?",afterSubmitCardState,SkreturnMsg+"(蜜蜂)",cardId);


            record.remove("code").set("createTime", new Date()).set("returnJson", result)
                    .remove("id").set("cardId", cardId).set("id", userOrderNo);

            Record myData = new Record().set("id", userOrderNo).set("cardId", cardId).set("classId", record.getStr("classId")
            ).set("commodityId", record.getStr("commodityId")).set("commodityName", record.getStr("commodityName"))
                    .set("feedbackId", record.getStr("feedbackId")).set("feedbackValue", record.getStr("feedbackValue"))
                    .set("discount", record.getStr("discount")).set("createTime", new Date()).set("returnCode", resultMap.get("code"))
                    .set("returnMsg", resultMap.get("message"))
                    .set("returnJson", result).set("cardNumber", record.getStr("cardNumber")).set("cardPassword", record.getStr("cardPassword"))
                    .set("orderId", record.getStr("orderId")).set("memberId", record.getStr("memberId")).set("imgPath", record.getStr("imgPath"))
                    .set("className", record.getStr("className"));

            Db.save("card_send_logs", "id", myData);

            Syslog.info("推送蜜蜂台结束，返回结果为：" + result);

            cache.setex("card_send_logs" + cacheCardId, 1800, myData);

        } catch (Exception e) {

            Syslog.error(e);

        }

    }




    public static String sign(Map<String,Object> map) {
        String sign = "";

        try {
            for(Map.Entry<String, Object> entry : map.entrySet()){
                String mapKey = entry.getKey();

                sign =sign+ mapKey+entry.getValue();

                System.out.println(mapKey+":"+entry.getValue());
            }
            sign=sign+appSecret;


            Syslog.info("代签名字符串>>>>    "+sign);


            sign = MD5.md5(sign);
        } catch (Exception e) {
            e.printStackTrace();

        }

        return sign;

    }


    /**
     * @param strings
     */

    public static void main(String[] strings) {

        try {

            String str=getToken();


            System.out.println(str);


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * getToken
     */
    public  static  String getToken(){

        Map<String,Object> parameter=new LinkedHashMap<>();

        parameter.put("action","login");

        parameter.put("app_key",appkey);

        parameter.put("password",password);

        String time=System.currentTimeMillis()+"";

        time=time.substring(0,10);

        int intTime=Integer.parseInt(time);

        parameter.put("time",intTime);

        parameter.put("token","");

        parameter.put("username",userCode);


        String sign=sign(parameter);

        parameter.put("sign",sign);

        System.out.println("请求数据>>");

        System.out.println(JsonUtil.getJsonStr(parameter));


        String result=HttpKit.post(cardSubmitUrl,JsonUtil.getJsonStr(parameter));

        System.out.println(result);

        Map<String,Object> resultMap=JsonUtil.getMapFromJsonObjStr(result);

        return resultMap.get("data")+"";
    }









}
